<template>
    <div class="main_left_userinfo">
        <div class="main_left_userinfo_above">
            <div class="main_left_userinfo_above_one">
                <a-image :src="userinfo.avatar" class="main_left_userinfo_above_one_avatar" alt="头像"/>
                <div class="main_left_userinfo_above_one_userinfo">
                    <div class="main_left_userinfo_above_one_item">
                        <div class="main_left_userinfo_above_one_item_1">昵称：</div>
                        <div>{{ userinfo.nickname }}</div>
                    </div>
                    <div class="main_left_userinfo_above_one_item">
                        <div class="main_left_userinfo_above_one_item_1">性别：</div>
                        <div>{{ userinfo.sex === '0' ? '男' : '女' }}</div>
                    </div>
                    <div class="main_left_userinfo_above_one_item">
                        <div class="main_left_userinfo_above_one_item_1">积分：</div>
                        <div>{{ userinfo.integral }}</div>
                    </div>
                    <div class="main_left_userinfo_above_one_item">
                        <div class="main_left_userinfo_above_one_item_1">手机号：</div>
                        <div>{{ userinfo.mobile }}</div>
                    </div>
                    <div class="main_left_userinfo_above_one_item">
                        <div class="main_left_userinfo_above_one_item_1">邮箱：</div>
                        <div>{{ userinfo.email }}</div>
                    </div>
                    <div class="main_left_userinfo_above_one_item">
                        <div class="main_left_userinfo_above_one_item_1">出生年月日：</div>
                        <div>{{ userinfo.birthday }}</div>
                    </div>
                </div>
                <div style="display: flex;">
                    <a-button @click="showModal" class="main_left_userinfo_above_one_update" type="primary" ghost>修改
                    </a-button>
                </div>
            </div>
            <div class="main_left_userinfo_above_two">
                <div class="main_left_userinfo_above_two_item">
                    <img src="@/assets/img/personalCenter/粉丝.png" class="main_left_userinfo_above_two_item_img"
                         alt="粉丝">
                    <div class="main_left_userinfo_above_two_item_1">粉丝数</div>
                    <div class="main_left_userinfo_above_two_item_2">{{ userinfo.fansCount }}</div>
                </div>
                <div class="main_left_userinfo_above_two_item">
                    <img src="@/assets/img/personalCenter/关注.png" class="main_left_userinfo_above_two_item_img"
                         alt="关注">
                    <div class="main_left_userinfo_above_two_item_1">关注数</div>
                    <div class="main_left_userinfo_above_two_item_2">{{ userinfo.attentionCount }}</div>
                </div>
                <div class="main_left_userinfo_above_two_item">
                    <img src="@/assets/img/personalCenter/回复.png" class="main_left_userinfo_above_two_item_img"
                         alt="回复">
                    <div class="main_left_userinfo_above_two_item_1">回复数</div>
                    <div class="main_left_userinfo_above_two_item_2">{{ userinfo.replyCount }}</div>
                </div>
            </div>
            <div class="main_left_userinfo_above_three">
                <div class="main_left_userinfo_above_three_item">
                    <div class="main_left_userinfo_above_three_item_introduction">简介：</div>
                    <div>{{ userinfo.introduction === null ? '空空如也' : userinfo.introduction }}</div>
                </div>
            </div>
        </div>
        <a-modal
                ref="modalRef"
                v-model:visible="visible"
                :wrap-style="{ overflow: 'hidden' }"
                @ok="handleOk"
                cancelText="取消"
                okText="确认"
        >
            <a-form :label-col="{ span: 4 }">
                <a-form-item label="头像">
                    <a-upload
                            class="avatar-uploader"
                            :show-upload-list="false"
                            :action="imgUrl"
                            :before-upload="beforeUpload"
                            @change="handleChange"
                    >
                        <img :src="userinfo.avatar"
                             style="width: 150px;height: 150px;border-radius: 50%;cursor: crosshair;"
                             alt="头像"/>
                    </a-upload>
                </a-form-item>
                <a-form-item label="昵称">
                    <a-input v-model:value="userinfo.nickname"/>
                </a-form-item>
                <a-form-item label="性别">
                    <a-radio-group v-model:value="userinfo.sex">
                        <a-radio :value="'0'">男</a-radio>
                        <a-radio :value="'1'">女</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label="手机号">
                    <a-input v-model:value="userinfo.mobile" disabled/>
                </a-form-item>
                <a-form-item label="邮箱">
                    <a-input v-model:value="userinfo.email"/>
                </a-form-item>
                <a-form-item label="出生年月日">
                    <a-space direction="vertical">
                        <a-date-picker v-model:value="userinfo.birthday" valueFormat="YYYY-MM-DD"/>
                    </a-space>
                </a-form-item>
                <a-form-item label="简介">
                    <a-textarea v-model:value="userinfo.introduction"/>
                </a-form-item>
            </a-form>
            <template #title>
                <div ref="modalTitleRef" style="width: 100%; cursor: move">修改</div>
            </template>
            <!-- 拖拽 -->
            <template #modalRender="{ originVNode }">
                <div :style="transformStyle">
                    <component :is="originVNode"/>
                </div>
            </template>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import {computed, CSSProperties, ref, watch, watchEffect} from "vue";
import {Userinfo} from "@/model/personalCenter/userinfo";
// @ts-ignore
import cookie from 'js-cookie'
import {useDraggable} from '@vueuse/core';
import {updateUserinfo} from "@/api/personalCenter/userinfo";
import {message} from "ant-design-vue";
import type {UploadChangeParam, UploadProps} from 'ant-design-vue';

const getBase64 = (img: Blob, callback: (base64Url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
}

//上传的地址
let imgUrl = ref<string>('');
//加载动画
const loading = ref<boolean>(false);

const handleChange = (info: UploadChangeParam) => {
    if (info.file.status === 'uploading') {
        loading.value = true;
        return;
    }
    if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, (base64Url: string) => {
            if (info.file.response.code == 400) {
                message.warn("图片不合法!")
                message.warn("图片不合法!")
            } else {
                userinfo.value.avatar = info.file.response.data.url;
                loading.value = false;
            }
        });
    }
    if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
    }
};

//上传文件之前执行
const beforeUpload = (file: UploadProps['fileList'][number]) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片大小必须小于2MB!');
    }
    return isJpgOrPng && isLt2M;
};

//是否显示对话框
const visible = ref<boolean>(false);
const modalTitleRef = ref<any>(null);

//显示对话框
const showModal = () => {
    visible.value = true;
};
const {x, y, isDragging} = useDraggable(modalTitleRef);

//用户修改信息
const handleOk = () => {
    updateUserinfo(userinfo.value).then((res) => {
        if (res.data.code === 400) {
            message.warn(res.data.message)
        } else {
            visible.value = false;
        }
    })
};

const startX = ref<number>(0);
const startY = ref<number>(0);
const startedDrag = ref(false);
const transformX = ref(0);
const transformY = ref(0);
const preTransformX = ref(0);
const preTransformY = ref(0);
const dragRect = ref({left: 0, right: 0, top: 0, bottom: 0});
watch([x, y], () => {
    if (!startedDrag.value) {
        startX.value = x.value;
        startY.value = y.value;
        const bodyRect = document.body.getBoundingClientRect();
        const titleRect = modalTitleRef.value.getBoundingClientRect();
        dragRect.value.right = bodyRect.width - titleRect.width;
        dragRect.value.bottom = bodyRect.height - titleRect.height;
        preTransformX.value = transformX.value;
        preTransformY.value = transformY.value;
    }
    startedDrag.value = true;
});
watch(isDragging, () => {
    if (!isDragging) {
        startedDrag.value = false;
    }
});

watchEffect(() => {
    if (startedDrag.value) {
        transformX.value =
            preTransformX.value +
            Math.min(Math.max(dragRect.value.left, x.value), dragRect.value.right) -
            startX.value;
        transformY.value =
            preTransformY.value +
            Math.min(Math.max(dragRect.value.top, y.value), dragRect.value.bottom) -
            startY.value;
    }
});
const transformStyle = computed<CSSProperties>(() => {
    return {
        transform: `translate(${transformX.value}px, ${transformY.value}px)`,
    };
});

//用户信息
const userinfo = ref<Userinfo>({
    id: 0,
    mobile: '',
    nickname: '',
    sex: '',
    birthday: '',
    avatar: '',
    email: '',
    integral: 0,
    introduction: '',
    fansCount: 0,
    attentionCount: 0,
    replyCount: 0
})

//从cookie中获取用户信息
const getUserinfo = () => {
    userinfo.value = JSON.parse(cookie.get('userinfo'))
    imgUrl.value = import.meta.env.VITE_BASE_URL + '/thirdParty/oss/upload/' + userinfo.value.id
}

getUserinfo()
</script>

<style lang="less" scoped>
.main_left_userinfo {
  margin-left: 15%;
  width: 70%;

  .main_left_userinfo_above {
    margin-top: 2%;

    .main_left_userinfo_above_one {
      display: flex;
      background-color: white;

      :deep(.main_left_userinfo_above_one_avatar) {
        width: 200px;
        height: 200px;
        border-radius: 50%;
        margin: 10px;
      }

      .main_left_userinfo_above_one_userinfo {
        width: 100%;
        margin-left: 1%;
        align-items: center;

        .main_left_userinfo_above_one_item {
          margin-top: 1%;
          display: flex;
          font-size: 15px;
          padding: 3px;
          width: 100%;

          .main_left_userinfo_above_one_item_1 {
            width: 100px;
          }
        }
      }

      .main_left_userinfo_above_one_update {
        margin-left: auto;
        margin-right: 20px;
        margin-top: 5px;
        font-size: 15px;
      }
    }

    .main_left_userinfo_above_two {
      display: flex;
      align-items: center;
      margin-top: 2%;
      background-color: white;
      justify-content: center;

      .main_left_userinfo_above_two_item {
        margin: 60px 80px;
        font-size: 30px;
        font-weight: bold;

        .main_left_userinfo_above_two_item_img {
          width: 100px;
          height: 100px;
        }

        .main_left_userinfo_above_two_item_1 {
          color: #FF7F50;
        }

        .main_left_userinfo_above_two_item_2 {
          text-align: center;
        }
      }
    }

    .main_left_userinfo_above_three {
      margin-top: 2%;
      background-color: white;
      min-height: 200px;
      max-height: 290px;

      .main_left_userinfo_above_three_item {
        display: flex;
        padding: 1%;
        font-size: 20px;
        word-break: break-word;

        .main_left_userinfo_above_three_item_introduction {
          white-space: nowrap;
        }
      }
    }
  }
}
</style>